import React from 'react';
import { connect } from 'dva';
import { Picker,Drawer, List, NavBar,Icon, InputItem , TabBar,Pagination ,Toast ,Button,TextareaItem,WhiteSpace,} from 'antd-mobile';
import { Rate} from 'antd';
import { createForm } from 'rc-form';
import Reset from '../../style/ResetInput.less'
import { Link } from 'dva/router';
import style from '../../style/App.less'
import reqwest from 'reqwest';
import {numvail,selectvail,datevali_deta} from '../../utils/Validator.js'
import PropTypes from 'prop-types';
import { Editor } from 'react-draft-wysiwyg'
import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css';
class ClueCreate extends React.Component{
		constructor(props){
		super(props);
		this.state={
			reginos:[],
			disable:true,
			list:JSON.parse(window.sessionStorage["ism"]),
      // contentState:JSON.parse(JSON.parse(window.sessionStorage['ism']).remark),
      contentState:undefined,
      pound:0
		}
	}
	loadServer(params={}){
		// console.log(data)
		const _this = this;
    let _date = new Date();
    params.remark.date=datevali_deta(_date);
    params.remark.name=JSON.parse(window.localStorage['setting']).name;
		reqwest({
      url: window.host+'/api/clues/update_me',
      method: 'post',
      crossOrigin: true,
      type: 'json',
      data:{ access_token:localStorage['token'],
      id:_this.state.list.id,
      clue:{name:params.name,mobile:params.mobile.replace(/\s+/g, ""),address:params.address,pound:_this.state.pound,remark:JSON.stringify(params.remark)}}
    }).then((data) => {
      if(data.status=='success'){
          Toast.success(
          '保存成功',
          1,
          ()=>{
            // window.localStorage['token']=data.token;
            // window.localStorage['curloe']=data.current_user.role;
            // // debugger
            // window.localStorage['menu']=JSON.stringify(data.menu);
            // window.localStorage['cgj_id']=data.current_user.cgj_user_id;
            // window.localStorage['account_type']=data.current_user.account_type;
            // window.localStorage['userrr_id']=data.current_user.id;
            window.location.hash='/hfive/clues';
          }
        )
        
      }else{
        Toast.fail(
          data.msg,
          1
        )
      }
    }).fail( (err, msg) =>{
       Toast.offline('网络连接失败!!!', 1);
    });
	}
	handleSubmit(e){
		e.preventDefault();
    let _this=this;
    // this.props.form.getFieldError('cha_name')
    this.props.form.validateFields((err, values) => {
        // console.log(this.state.payMethods.match(/\d+/g));
        // let chaname= values.chaname!==undefined?values.chaname.match(/\d+/g):null;
      if (!err  ) {
        console.log('Received values of form: ', values);
        // valiues
      	_this.loadServer({
      		name:values.contact,mobile:values.phone,address:values.address,remark:values.remark,pound:_this.state.pound,
      	})
      }
    });
	}
  remarkMount(){
    let _rmNode=JSON.parse(window.sessionStorage['ism']).remark!=="null"?JSON.parse(window.sessionStorage['ism']).remark.split('~'):['null'];
    // console.log(_rmNode[0]==='null')
    let _even={unde:"undefined",entityMap:undefined,blocks:[]};
    // debugger
    let _node,_node1;
    let _json;
    // _json=_rmNode[0]===""?'null':undefined
    _rmNode[0]==="null"||_rmNode[0]===""?'null':_rmNode.map((data,index)=>{
      // console.log(200)
      _node1=data[index]===undefined?undefined:JSON.parse(data)
      // console.log(100)
      // if(data===undefined){
      //  return
      // }
      // contentState.blocks[index]=_node.blocks;
      // console.log(contentState)
      if(data[index]!==undefined){
      // return <p key={index}>
          {JSON.parse(data).blocks.map((dats,index)=>{
            if(_even.unde==="undefined"){
              _even.entityMap=JSON.parse(data).entityMap;
              // _even.blocks=[]
              _even.blocks.push(dats)
              _even.unde='1'
            }else{
              _even.blocks.push(dats)
            }
            // console.log(dats)
            // return <span key={dats.key} className={`${style.reset_remark}`} >{dats.text}</span>

          })}
          // <span style={{textAlign:'right',display:'block'}}>{JSON.parse(data).date}</span>
        // </p>
      }
    })
    this.setState({contentState:_even})
  }
	componentWillMount(){
    if(JSON.parse(window.sessionStorage['ism']).remark!==null&&JSON.parse(window.sessionStorage['ism']).remark!==""){
      this.remarkMount()
    }
		// let _regions=[];
		// if(!!sessionStorage['regions']){
		// 	JSON.parse(sessionStorage['regions']).map(function(data,index){
		// 		_regions.push({
		// 			value:data.id,
		// 			label:data.name
		// 		})
		// 	})
		// }
		// this.setState({reginos:_regions})
	}
  onContentStateChange(contentState){
    this.setState({
      contentState
    });
  }
	render(){
		console.log(this.state.list)
		 const { getFieldProps , getFieldError} = this.props.form;
		 const _this =this;
     // console.log(this.state.contentState)
     // debugger
		 return(
			<div className={`${style.layout}`}>
				<List className={`${Reset.tel_list_header}`} renderHeader={() => '线索'}>
          <InputItem
	          clear
            className={`${Reset.tel_input}`}
	          error={!!getFieldError('contact')}
	          onErrorClick={() => {
	            alert(getFieldError('contact').join('、'));
	          }}
            {...getFieldProps('contact',{
            	initialValue:this.state.list.name,
            	rules:[{required:true,message:'客户姓名'}]
            })}
            placeholder="客户姓名"
          >联系人</InputItem>
          <InputItem
	          clear
            className={`${Reset.tel_input}`}
	          error={!!getFieldError('phone')}
	          onErrorClick={() => {
	            alert(getFieldError('phone').join('、'));
	          }}
            {...getFieldProps('phone',{
            	initialValue:this.state.list.mobile,
            	rules:[{required:true,message:'请输入手机号码',len:11,validator:(rule,value,callback)=>{
								numvail(rule,value.replace(/\s+/g, ""),callback)
							}}]
            })}
            type='phone'
            placeholder="手机号码"
          >手机号码</InputItem>
          <InputItem
	          clear
            className={`${Reset.tel_input}`}
	          error={!!getFieldError('address')}
	          onErrorClick={() => {
	            alert(getFieldError('address').join('、'));
	          }}
            {...getFieldProps('address',{
            	initialValue:this.state.list.address,
            	rules:[{required:true,message:'请输入地址'}]
            })}
            placeholder='地址'
          >地址</InputItem>
          <List.Item
            className={`${Reset.tel_input}`}
            {...getFieldProps('pound',{
              rules:[{message:'优先级'}]
            })}
            placeholder='地址'
          >优先级<Rate style={{fontSize:'0.4rem',marginLeft:'0.7rem'}} defaultValue={this.state.ism==null?this.state.pound:this.state.ism.pound} onChange={(e)=>this.setState({pound:e})} allowHalf={false} /></List.Item>
          <List className={`${Reset.tel_list_header}`} renderHeader={() => '备注'} style={{background:'#f5f5f9'}}>
	          <Editor {...getFieldProps('remark', {
                // initialValue: '备注'
              })} onContentStateChange={()=>this.onContentStateChange} contentState={this.state.contentState}
             toolbarHidden editorStyle={{fontSize:'0.25rem',margin:0}} wrapperStyle={{border:'1px solid #fcfcfc',borderRadius:4,width:'100vw',minHeight:'2rem'}} />
	        </List>
        </List>
        <Button className={`${Reset.btn_moblie} ${Reset.tel_btn}`} onClick={this.handleSubmit.bind(this)}  type='primary'>保存</Button>
        <WhiteSpace size="sm" />
			</div>
	 	)
		
	}
}

const ClueForm = createForm()(ClueCreate);
export default connect()(ClueForm)